package org.spring.aicloud.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.simpleframework.xml.core.Validate;
import org.spring.aicloud.entity.User;
import org.spring.aicloud.entity.dto.UserDTO;
import org.spring.aicloud.service.IUserService;
import org.spring.aicloud.util.NameUtil;
import org.spring.aicloud.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
@Tag(name = "用户控制器")
public class UserController {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private IUserService userService;
    //Spring Security自带的密码加密工具
    //在SecurityConfig中已经配置过了
    @Resource
    private PasswordEncoder passwordEncoder;
    //从配置文件里读取jst的密钥
    @Value("${jwt.secret}")
    private String jwtSecret;

    /**
     * 登录方法
     */
    @PostMapping("/login")
    @Operation(summary = "登录方法")
    @Parameters({
        @Parameter(name = "userDTO",description = "userDTO对象")
    })
    public ResponseEntity login(@Validate UserDTO userDTO, HttpServletRequest request) {
        //1.非空判断 根据@Validate来验证
        //2.验证图片验证码
        //先从redis中获取到验证码的值
        String redisCaptchaKey = NameUtil.getCaptchaName(request);
        String redisCaptcha = (String) redisTemplate.opsForValue().get(redisCaptchaKey);
        //如果在redis中获取不到验证码，则说明验证码已失效
        if (!StringUtils.hasLength(redisCaptcha)) {
            return ResponseEntity.fail("验证码已失效");
        }
        //如果redis中的验证码和用户输入的验证码不一致，则说明输入错误
        if (!redisCaptcha.equalsIgnoreCase(userDTO.getCaptcha())) {
            return ResponseEntity.fail("输入验证码错误！");
        }
        //3.验证用户名和密码
        //从数据库中根据username来读取
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", userDTO.getUsername());
        User user = userService.getOne(queryWrapper);
        //读取完成之后，判断是否为空
        //如果为空，则说明用户名不存在
        //不为空，则根据数据库中的密码和传递过来的密码进行验证(加盐判断)
        if (user != null && passwordEncoder.matches(userDTO.getPassword(),user.getPassword())) {
            //登录成功之后，生成jwt，并且返回给客户端
            //创建jwt的载荷
            HashMap<String,Object> payload = new HashMap<>();
            payload.put("uid",user.getUid());
            payload.put("username",user.getUsername());
            //生成Token
            String token = JWTUtil.createToken(payload,jwtSecret.getBytes());
            //除了要返回token之外，还要将用户名返回，用于左上角的显示
            HashMap<String,String> result = new HashMap<>();
            result.put("jwt",token);
            result.put("username",user.getUsername());
            return ResponseEntity.success(result);
        }
        return ResponseEntity.fail("用户名或者密码不正确！");
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public ResponseEntity register(@Validate User user) {
        //密码加盐处理
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //添加用户到数据库
        boolean result = userService.save(user);
        if (result) {
            return ResponseEntity.success(result);
        }
        return ResponseEntity.fail("注册失败,请重试!");
    }

}
